import React, { useEffect, useState } from 'react';
import { 
  Tag, Card, Form, Select, DatePicker, Button, 
  Space, Table, message, Popconfirm, Tabs, 
  Input, Divider, Tooltip, Modal, Upload, Dropdown, 
  Menu, List, Avatar
} from 'antd';
import { 
  CheckCircleOutlined, ClockCircleOutlined, 
  CloseCircleOutlined, ImportOutlined, 
  PlusOutlined, ExportOutlined, 
  SortAscendingOutlined, DeleteOutlined, 
  UpCircleOutlined, SearchOutlined, 
  ReloadOutlined, UnorderedListOutlined, 
  UndoOutlined, UploadOutlined, DownloadOutlined,
  ArrowUpOutlined, ArrowDownOutlined,
  AppstoreOutlined, TableOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import RefundsService from '../../services/RefundsService';
import '../components.css';

const { Option } = Select;
const { TabPane } = Tabs;

const RefundList = () => {
  // 状态管理
  const [refunds, setRefunds] = useState([]);
  const [filteredRefunds, setFilteredRefunds] = useState([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({current: 1, pageSize: 10, total: 0,});
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [importLoading, setImportLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [sortConfig, setSortConfig] = useState({key: null, direction: 'ascend'});
  const [viewMode, setViewMode] = useState('table');

  // 获取退款数据
  const getAllRefunds = async (params = {}) => {
    setLoading(true);
    try {
      const response = await RefundsService.getAllRefunds(params);
      const data = response.data.map(item => ({
        ...item,
        key: item.id,
      }));
      setRefunds(data);
      setFilteredRefunds(data);
      setPagination({
        ...pagination,
        total: data.length,
      });
    } catch (error) {
      message.error('加载退款数据失败');
      console.error('获取退款数据错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    getAllRefunds();
  }, []);

  // 标签页切换处理
  const handleTabChange = (key) => {
    setActiveTab(key);
    filterDataByTab(key, form.getFieldsValue());
  };

  // 根据标签页筛选数据
  const filterDataByTab = (tabKey, formValues) => {
    let filteredData = [...refunds];
    
    // 标签页筛选
    if (tabKey === 'mine') {
      filteredData = refunds.filter(item => item.responsiblePerson === '当前用户');
    } else if (tabKey === 'next') {
      filteredData = refunds.filter(item => item.responsiblePerson !== '当前用户');
    }
    
    // 表单筛选条件
    filteredData = applyFormFilters(filteredData, formValues);
    
    setFilteredRefunds(filteredData);
    setPagination(prev => ({
      ...prev,
      total: filteredData.length,
      current: 1,
    }));
  };

  // 应用表单筛选条件
  const applyFormFilters = (data, values) => {
    let result = [...data];
    
    // 关键词搜索
    if (values?.keyword) {
      const keyword = values.keyword.toLowerCase();
      result = result.filter(item => 
        (item.refundNumber && item.refundNumber.toLowerCase().includes(keyword)) || 
        (item.relatedCustomer && item.relatedCustomer.toLowerCase().includes(keyword))
      );
    }
    
    // 审批状态筛选
    if (values?.approvalstatus && values.approvalstatus !== 'all') {
      result = result.filter(item => 
        item.approvalStatus === values.approvalstatus
      );
    }
    
    // 负责人员筛选
    if (values?.responsibleperson && values.responsibleperson !== 'all') {
      result = result.filter(item => 
        item.responsiblePerson === values.responsibleperson
      );
    }
    
    // 退款日期筛选
    if (values?.refundDate) {
      const selectedDate = values.refundDate.format('YYYY-MM-DD');
      result = result.filter(item => 
        item.refundDate === selectedDate
      );
    }
    
    // 提交时间筛选
    if (values?.submitTime) {
      const submitDate = values.submitTime.format('YYYY-MM-DD');
      result = result.filter(item => 
        item.submitTime === submitDate
      );
    }
    
    return result;
  };

  // 搜索处理
  const handleSearch = (values) => {
    filterDataByTab(activeTab, values);
  };

  // 重置搜索表单
  const onReset = () => {
    form.resetFields();
    filterDataByTab(activeTab, {});
  };

  // 删除退款
  const deleteRefund = async (id) => {
    try {
      await RefundsService.deleteRefund(id);
      message.success('删除成功');
      getAllRefunds();
    } catch (error) {
      message.error('删除失败');
      console.error('删除退款错误:', error);
    }
  };

  // 排序函数
  const requestSort = (key) => {
    let direction = 'ascend';
    if (sortConfig.key === key && sortConfig.direction === 'ascend') {
      direction = 'descend';
    }
    setSortConfig({ key, direction });
    
    // 执行排序
    const sortedData = [...filteredRefunds].sort((a, b) => {
      // 处理可能为null或undefined的值
      const valueA = a[key] || '';
      const valueB = b[key] || '';
      
      if (valueA < valueB) {
        return direction === 'ascend' ? -1 : 1;
      }
      if (valueA > valueB) {
        return direction === 'ascend' ? 1 : -1;
      }
      return 0;
    });
    
    setFilteredRefunds(sortedData);
  };

  // 获取排序图标
  const getSortIcon = (key) => {
    if (sortConfig.key !== key) {
      return <SortAscendingOutlined />;
    }
    return sortConfig.direction === 'ascend' ? <ArrowUpOutlined /> : <ArrowDownOutlined />;
  };

  // 表格列定义
  const columns = [
    {
      title: (<span onClick={() => requestSort('refundNumber')}>退款编号 {getSortIcon('refundNumber')}</span>),
      dataIndex: 'refundNumber',
      key: 'refundNumber',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: (<span onClick={() => requestSort('relatedCustomer')}>关联客户 {getSortIcon('relatedCustomer')}</span>),
      dataIndex: 'relatedCustomer',
      key: 'relatedCustomer',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: (<span onClick={() => requestSort('relatedOrder')}>关联订单 {getSortIcon('relatedOrder')}</span>),
      dataIndex: 'relatedOrder',
      key: 'relatedOrder',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: (<span onClick={() => requestSort('refundAmount')}>退款金额 {getSortIcon('refundAmount')}</span>),
      dataIndex: 'refundAmount',
      key: 'refundAmount',
      align: 'center',
      render: (amount) => amount ? `¥${parseFloat(amount).toFixed(2)}` : '¥0.00',
    },
    {
      title: (<span onClick={() => requestSort('refundMethod')}>退款方式 {getSortIcon('refundMethod')}</span>),
      dataIndex: 'refundMethod',
      key: 'refundMethod',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: (<span onClick={() => requestSort('refundDate')}>退款日期 {getSortIcon('refundDate')}</span>),
      dataIndex: 'refundDate',
      key: 'refundDate',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: (<span onClick={() => requestSort('approvalStatus')}>审批状态 {getSortIcon('approvalStatus')}</span>),
      dataIndex: 'approvalStatus',
      key: 'approvalStatus',
      align: 'center',
      render: (status) => {
        const statusMap = {
          approved: {
            icon: <CheckCircleOutlined />,
            color: 'green',
            text: '已通过',
          },
          pending: {
            icon: <ClockCircleOutlined />,
            color: 'blue',
            text: '待审批',
          },
          denied: {
            icon: <CloseCircleOutlined />,
            color: 'red',
            text: '被否决',
          },
          rejected: {
            icon: <CloseCircleOutlined />,
            color: 'yellow',
            text: '被驳回',
          },
          revoked: {
            icon: <UndoOutlined />,
            color: 'orange',
            text: '已撤销',
          },
        };
        
        const currentStatus = statusMap[status] || { 
          icon: null, 
          color: 'default', 
          text: '未知状态' 
        };
        
        return (
          <Tag icon={currentStatus.icon} color={currentStatus.color}>
            {currentStatus.text}
          </Tag>
        );
      },
    },
    {
      title: (<span onClick={() => requestSort('responsiblePerson')}>负责人员 {getSortIcon('responsiblePerson')}</span>),
      dataIndex: 'responsiblePerson',
      key: 'responsiblePerson',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      fixed: 'right',
      width: 220,
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="详情">
            <Button icon={<EyeOutlined />}>
              <Link to={`/refunddetail/${record.id}`}>详情</Link>
            </Button>
          </Tooltip>
          <Tooltip title="编辑">
            <Button type="primary" icon={<UpCircleOutlined />}>
              <Link to={`updaterefund/${record.id}`} style={{ color: "white" }}>编辑</Link>
            </Button>
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm title="确定要删除此退款记录吗?" onConfirm={() => deleteRefund(record.id)} okText="确定" cancelText="取消">
              <Button type="danger" icon={<DeleteOutlined />}>删除</Button>
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  // 显示导入弹窗
  const showImportModal = () => {
    setImportModalVisible(true);
  };

  // 隐藏导入弹窗
  const hideImportModal = () => {
    setImportModalVisible(false);
    setFileList([]);
  };

  // 处理文件上传变化
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 执行导入操作
  const handleImport = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择文件');
      return;
    }

    try {
      setImportLoading(true);
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files', file.originFileObj);
      });
    const response = await RefundsService.importRefunds(formData);
      
      if (response.status === 200) {
        message.success('导入成功！');
        getAllRefunds();
        hideImportModal();
      } else {
        throw new Error(response.data?.message || '导入失败');
      }
    } catch (error) {
      console.error('导入失败:', error);
      message.error(error.response?.data?.message || '导入失败，请重试！');
    } finally {
      setImportLoading(false);
    }
  };

  // 导出功能
  const handleExport = async () => {
    try {
      setExportLoading(true);
      
      // 获取当前筛选条件
      const filterValues = form.getFieldsValue();
      const tabFilter = activeTab;
      
      // 调用导出API
      const response = await RefundsService.exportRefunds({
        ...filterValues,
        tabFilter
      });
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      
      // 从Content-Disposition中获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let fileName = '退款数据.xlsx';
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename=(.+)/);
        if (fileNameMatch && fileNameMatch.length === 2) {
          fileName = fileNameMatch[1];
        }
      }
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      
      message.success('导出成功！');
    } catch (error) {
      console.error('导出失败:', error);
      message.error(error.response?.data?.message || '导出失败，请重试！');
    } finally {
      setExportLoading(false);
    }
  };

  // 排序菜单
  const sortMenu = (
    <Menu>
      <Menu.Item key="amountAsc" onClick={() => requestSort('refundAmount')}>
        按金额升序
      </Menu.Item>
      <Menu.Item key="amountDesc" onClick={() => requestSort('refundAmount', 'descend')}>
        按金额降序
      </Menu.Item>
      <Menu.Item key="dateAsc" onClick={() => requestSort('refundDate')}>
        按日期升序
      </Menu.Item>
      <Menu.Item key="dateDesc" onClick={() => requestSort('refundDate', 'descend')}>
        按日期降序
      </Menu.Item>
    </Menu>
  );

  // 卡片视图渲染
  const renderCardView = () => {
    return (
      <List
        grid={{ gutter: 16, column: 3 }}
        dataSource={filteredRefunds}
        loading={loading}
        renderItem={(item) => (
          <List.Item>
            <Card 
              title={`退款编号: ${item.refundNumber || '-'}`}
              actions={[
                <Tooltip title="详情" key="detail">
                  <Link to={`refunddetail/${item.id}`}>
                    <Button type="text" icon={<EyeOutlined />} />
                  </Link>
                </Tooltip>,
                <Tooltip title="编辑" key="edit">
                  <Link to={`updaterefund/${item.id}`}>
                    <Button type="text" icon={<UpCircleOutlined />} />
                  </Link>
                </Tooltip>,
                <Tooltip title="删除" key="delete">
                  <Popconfirm 
                    title="确定要删除此退款记录吗?" 
                    onConfirm={() => deleteRefund(item.id)} 
                    okText="确定" 
                    cancelText="取消"
                  >
                    <Button type="text" danger icon={<DeleteOutlined />} />
                  </Popconfirm>
                </Tooltip>
              ]}
            ><Card.Meta
                avatar={<Avatar icon={<UndoOutlined />} />}
                title={`客户: ${item.relatedCustomer || '-'}`}
                description={
                  <div>
                    <p>订单: {item.relatedOrder || '-'}</p>
                    <p>金额: {item.refundAmount ? `¥${parseFloat(item.refundAmount).toFixed(2)}` : '¥0.00'}</p>
                    <p>方式: {item.refundMethod || '-'}</p>
                    <p>日期: {item.refundDate || '-'}</p>
                    <p>负责人: {item.responsiblePerson || '-'}</p>
                    <Tag 
                      icon={getStatusIcon(item.approvalStatus)} 
                      color={getStatusColor(item.approvalStatus)}
                    >
                      {getStatusText(item.approvalStatus)}
                    </Tag>
                  </div>
                }
              />
            </Card>
          </List.Item>
        )}
      />
    );
  };

  // 获取状态图标
  const getStatusIcon = (status) => {
    const statusMap = {
      approved: <CheckCircleOutlined />,
      pending: <ClockCircleOutlined />,
      denied: <CloseCircleOutlined />,
      rejected: <CloseCircleOutlined />,
      revoked: <UndoOutlined />,
    };
    return statusMap[status] || null;
  };

  // 获取状态颜色
  const getStatusColor = (status) => {
    const colorMap = {
      approved: 'green',
      pending: 'blue',
      denied: 'red',
      rejected: 'yellow',
      revoked: 'orange',
    };
    return colorMap[status] || 'default';
  };

  // 获取状态文本
  const getStatusText = (status) => {
    const textMap = {
      approved: '已通过',
      pending: '待审批',
      denied: '被否决',
      rejected: '被驳回',
      revoked: '已撤销',
    };
    return textMap[status] || '未知状态';
  };

  // 切换视图模式
  const toggleViewMode = () => {
    setViewMode(viewMode === 'table' ? 'card' : 'table');
  };
  
  return (
    <div className="refund-management">
      <Card bordered={false}>
      {/* <Card bordered={false} title="退款管理"> */}
        {/* 顶部标签页 */}
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="全部退款" key="all" />
          <TabPane tab="我的退款" key="mine" />
          <TabPane tab="下属退款" key="next" />
        </Tabs>

        {/* 筛选表单 */}
        <Form form={form} name="search-form" onFinish={handleSearch} layout="vertical" className="search-form">
          <div className="search-fields" style={{display: 'flex', flexWrap: 'wrap', gap: '16px'}}>
            <Form.Item name="keyword" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Input placeholder="搜索关键词" allowClear prefix={<SearchOutlined />}/>
            </Form.Item>
            <Form.Item name="approvalstatus" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Select placeholder="审批状态" allowClear>
                <Option value="all">全部状态</Option>
                <Option value="approved">已通过</Option>
                <Option value="pending">待审批</Option>
                <Option value="denied">被否决</Option>
                <Option value="rejected">被驳回</Option>
                <Option value="revoked">已撤销</Option>
              </Select>
            </Form.Item>
            <Form.Item name="refundDate" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <DatePicker placeholder="退款日期" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="responsibleperson" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Select placeholder="负责人员" allowClear>
                <Option value="all">全部人员</Option>
                <Option value="贝生">贝生</Option>
                <Option value="罗齐">罗齐</Option>
                <Option value="当前用户">当前用户</Option>
              </Select>
            </Form.Item>
            <Form.Item name="submitTime" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <DatePicker placeholder="提交时间" style={{ width: '100%' }} />
            </Form.Item>
            <div className="form-actions">
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
              <Button onClick={onReset} icon={<ReloadOutlined />} style={{ marginLeft: 8 }}>重置</Button>
            </div>
          </div>
        </Form>

        <Divider />

        {/* 操作按钮 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />}>
             <Link to="../addrefund" style={{ color: 'white' }}>添加退款</Link>
            </Button>
            <Button icon={<ImportOutlined />} onClick={showImportModal}>导入</Button>
            <Button icon={<ExportOutlined />} onClick={handleExport} loading={exportLoading}>导出</Button>
          </Space>
          <Space>
            <Dropdown overlay={sortMenu} trigger={['click']}>
              <Button icon={<SortAscendingOutlined />}>排序</Button>
            </Dropdown>
            <Button 
              icon={viewMode === 'table' ? <AppstoreOutlined /> : <TableOutlined />} 
              onClick={toggleViewMode}>
              {viewMode === 'table' ? '卡片视图' : '表格视图'}
            </Button>
          </Space>
        </div>
        
        {/* 根据视图模式显示不同内容 */}
        {/* 退款数据表格 */}
        {viewMode === 'table' ? (
          <Table
            columns={columns}
            dataSource={filteredRefunds}
            loading={loading}
            bordered
            rowKey="id"
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
        ) : (
          renderCardView()
        )}

        {/* 导入弹窗 */}
        <Modal title="导入退款数据"
          visible={importModalVisible} onCancel={hideImportModal}
          footer={[
            <Button key="cancel" onClick={hideImportModal}>取消</Button>,
            <Button key="import" type="primary" 
              loading={importLoading} onClick={handleImport}
              icon={<ImportOutlined />}>开始导入</Button>,]}>
          <Upload multiple fileList={fileList}
            onChange={handleUploadChange}
            beforeUpload={() => false} // 阻止自动上传
            accept=".xlsx,.xls,.csv">
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
          <div style={{ marginTop: 16 }}>
            <p>支持格式: .xlsx, .xls, .csv</p>
            <p>文件大小限制: 10MB</p>
            <p>请确保文件格式与模板一致</p>
          </div>
        </Modal>
      </Card>
    </div>
  );
};

export default RefundList;